'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Image from 'next/image'
import Link from 'next/link'
import axios from 'axios'
import { API_CONFIG } from '../config';

interface Category {
  id: number
  pid: number
  type: string
  name: string
  createtime: number
  updatetime: number
  weigh: number
  status: string
}

interface Product {
  id: number
  name: string
  image: string
  price: string
  description: string
  stock: number
  status: string
  category_id: number
  create_time: string
  update_time: string
  is_home: number
}

const api = axios.create({
  baseURL: '/api',
  headers: {
    'Content-Type': 'application/json'
  }
})

export default function ShopPage() {
  const router = useRouter()
  const [categories, setCategories] = useState<Category[]>([])
  const [selectedCategory, setSelectedCategory] = useState<number>(0)
  const [products, setProducts] = useState<Product[]>([]);

  // 移除 useEffect 中的接口请求
  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await api.post('/shop')
        setCategories(response.data)
      } catch (error) {
        console.error('Failed to fetch categories:', error)
      }
    }

    fetchCategories()
    // 新增获取产品数据的逻辑
    const fetchProducts = async () => {
      try {
        const response = await api.post('/product', {
          id: selectedCategory
        });
        setProducts(response.data);
      } catch (error) {
        console.error('Failed to fetch products:', error);
      }
    };

    fetchProducts();
  }, [selectedCategory]);
  const addToCart = async (product: Product) => {
    try {
      // 1. 获取现有购物车数据
      const existingCart = localStorage.getItem('cart');
      const cart = existingCart ? JSON.parse(existingCart) : [];

      // 2. 检查商品是否已在购物车中
      const existingItemIndex = cart.findIndex((item:any) => item.id === product.id);

      if (existingItemIndex >= 0) {
        // 如果商品已存在，增加数量
        cart[existingItemIndex].quantity += 1;
      } else {
        // 如果商品不存在，添加新商品
        cart.push({
          id: product.id,
          name: product.name,
          price: product.price,
          image: product.image,
          quantity: 1
        });
      }

      // 3. 保存更新后的购物车数据
      localStorage.setItem('cart', JSON.stringify(cart));

      // 4. 显示成功提示
      alert('Added to cart successfully!');
    } catch (error) {
      console.error('Error adding to cart:', error);
      alert('Failed to add to cart');
    }
  };

  return (
    <div>
      {/* 分类选项卡 */}
      <div className="relative mb-6">
        <div className="absolute left-0 top-0 bottom-0 w-8 bg-gradient-to-r from-white to-transparent pointer-events-none z-10"></div>
        <div className="absolute right-0 top-0 bottom-0 w-8 bg-gradient-to-l from-white to-transparent pointer-events-none z-10"></div>
        
        <div className="overflow-x-auto scrollbar-hide">
          <div className="flex whitespace-nowrap space-x-2 py-2 px-4">
            {/* 添加"全部"选项 */}
            <button 
              className={`px-4 py-2 text-sm font-medium rounded-full min-w-max ${
                selectedCategory === 0 
                  ? 'bg-[#ffe4ed] text-[#ff4d8c]' 
                  : 'text-gray-600 hover:bg-[#fff5f8]'
              }`}
              onClick={() => setSelectedCategory(0)}
            >
              All Products
            </button>

            {/* 动态渲染分类按钮 */}
            {categories.map((category) => (
              <button
                key={category.id}
                className={`px-4 py-2 text-sm font-medium rounded-full min-w-max ${
                  selectedCategory === category.id 
                    ? 'bg-[#ffe4ed] text-[#ff4d8c]' 
                    : 'text-gray-600 hover:bg-[#fff5f8]'
                }`}
                onClick={() => setSelectedCategory(category.id)}
              >
                {category.name}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* 商品网格 */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3 md:gap-4">
        {products.map((product) => (
          <div key={product.id} className="border rounded-lg p-2 hover:shadow-md transition-shadow">
            <Link href={`/shop/${product.id}`}>
              <div className="w-full h-[180px] mb-2">
                <Image
                  src={`${API_CONFIG.BASE_URL}${product.image}`}
                  alt={product.name}
                  width={180}
                  height={180}
                  className="object-cover rounded-lg"
                  priority={product.id <= 4}
                  quality={75}
                />
              </div>
            </Link>
            <h3 className="text-xs font-medium mb-1 line-clamp-2 px-1">{product.name}</h3>
            <div className="flex items-center justify-between px-1">
              <span className="text-xs font-bold text-[#ff4d8c]">
                ${Number(product.price).toFixed(2)}
              </span>
              <button 
                onClick={() => addToCart(product)}
                className="bg-[#ff4d8c] text-white text-[10px] px-2 py-1 rounded hover:bg-[#ff3377] transition-colors"
              >
                Cart
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* Warning Notice */}
      <div className="mt-16 text-center text-gray-500">
        <p className="text-sm">         </p>
      </div>
    </div>
  )
}